import sys
import time
import os
from subprocess import Popen, PIPE
from utils.debug import *
from gui import Gui
from config import Config
from tv import TV

class Watch(Gui, TV):

    def __init__(self):
        '''
        Displaying the application's main window
        and handling tv watching processes
        '''
        Gui.__init__(self,'main', 'main_window', {
            'on_main_window_destroy' : self.quit,
            'on_quit_item_activate' : self.quit,
            'on_watch_button_toggled' : self._watch_button_toggled,
            'on_previous_button_clicked' : self._previous_button_clicked,
            'on_next_button_clicked' : self._next_button_clicked,
            'on_volume_button_value_changed' : self._volume_button_value_changed,
            'on_channel_list_item_activate' : self._channel_list_item_activate,
            'on_preferences_item_activate' : self._preferences_item_activate,
            'on_normal_size_item_activate' : self._normal_size_item_activate,
            'on_double_size_item_activate' : self._double_size_item_activate,
            'on_about_item_activate' : self._about_item_activate
        })
        
        self.connect(self.window, 'destroy', self.quit)
        self.connect(self.widget('about_dialog'), 'delete-event', self._about_dialog_close)
        self.connect(self.widget('about_dialog'), 'response', self._about_dialog_close)
        
        TV.__init__(self)
        TV.main_window = self
        self.conf = Config()
        self._status('off')
        
        # set volume to current Line-in volume
        import re
        v = Popen('amixer -c 0 get Line,0'.split(), stdout=PIPE).stdout.readlines()[5]
        if re.compile('\[(on|off)\]').findall(v, re.IGNORECASE)[0] == 'off':
            Popen('amixer -c 0 set Line,0 unmute'.split(), stdout=PIPE)
        volume = re.compile('([0-9]{1,3})\%').findall(v, re.IGNORECASE)[0]
        self.widget('volume_button').set_value(float(volume)/100.0)
        
        if self.conf.get_conf('autostart') == '1':
            self.widget('watch_button').set_active(True)
        
        self.run()
    
    def quit(self, widget):
        '''Remove temporary files and terminate the application'''
        TV.off(self)
        Gui.quit(self, widget)
    
    def _watch_button_toggled(self, widget):
        '''Watch TV button clicked (toggled active)'''
        if widget.get_active():
            # reload current settings - ConfigObj own method not working
            if hasattr(self, 'conf'):
                delattr(self, 'conf')
                self.conf = Config()
            self.on(self.widget('video_area'), self.conf.tv_command)
            self._change_channel(0)
        else:
            self._status('off')
            self._resize_screen(0)
            self.off()
    
    def _previous_button_clicked(self, widget):
        '''
        change to previous channel, it goes back to the 
        last channel if it's the first channel
        '''
        self._change_channel(-1)
    
    def _next_button_clicked(self, widget):
        '''
        change to next channel, it goes back to the 
        first channel if it's the last channel
        '''
        self._change_channel(1)
    
    def _volume_button_value_changed(self, widget, value):
        '''
        Change Line-in volume through amixer on 
        volume_button value changed through sliding bar
        '''
        from math import ceil
        c = 'amixer -c 0 set Line,0 %s%%' % ceil(value*100)
        Popen(c.split(), stdout=PIPE)
    
    def _channel_list_item_activate(self, widget):
        '''show channel list dialog'''
        from channel import Channel
        c = Channel()
    
    def _preferences_item_activate(self, widget):
        '''show preferences-dialog'''
        from pref import Preferences
        p = Preferences()
    
    def _normal_size_item_activate(self, widget):
        '''Resize screen to normal size (specified in main.conf - screen_size)'''
        self._resize_screen()
    
    def _double_size_item_activate(self, widget):
        '''Resize screen to double of size specified in main.conf - screen_size'''
        self._resize_screen(2)
    
    def _about_item_activate(self, widget):
        '''Show about dialog'''
        self.widget('about_dialog').run()
    
    def _about_dialog_close(self, widget, response):
        '''Hide about-dialog but not destroying it, so that it can be shown later'''
        self.widget('about_dialog').hide()
        return True
    
    def _change_channel(self, value):
        '''Changing channel'''
        self.change_channel(value)
        if hasattr(self, '_player'):
            self._status('watch')
        else:
            self._status('off') 
    
    def _status(self, activity='off', message=''):
        '''
        Set status bar messages, using preset activity:
        'off', 'watch', 'record', 'scan'
        '''
        if activity == 'off':
            m = 'TV is off (Channel: %s)' % self.conf.channels[1][self._channel-1][1]
        elif activity == 'watch':
            m = 'Now watching: %s' % self.conf.channels[1][self._channel-1][1]
        elif activity == 'scan-start':
            m = 'Scanning TV...'
        elif activity == 'scan-stop':
            m = 'Finish scanning TV'
        self.widget('status_label').set_label('<small>%s</small>' % m)
    
    def _resize_screen(self, factor=1):
        '''
        Resize video_area by multiplying config screen_size with the f (factor)
        After resizing video_area, we need to resize the main_window also, but keeping its default_width
        '''
        if hasattr(self, '_player'):
            if not hasattr(self, '_current_screen_size'):
                # TODO: fix this equation making it dynamic (not using hard-coded value)
                self._current_screen_size = self.window.get_size()[0], self.window.get_size()[1]-48
            _w, _h = self._current_screen_size
            w, h = _w*factor, _h*factor
            if factor == 0:
                w, h = 1, 1
                self.widget('video_area').set_size_request(self.conf.screen_size[0], 0)
            self.window.resize(w, h)
